﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System;
using System.IO;
using DotNetNuke.Tests.UI.WatiN.Common;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using Gallio.Framework.Pattern;
using MbUnit.Framework;
using WatiN.Core;
using DotNetNuke.Tests.UI.WatiN.Common.WatiNObjects;

namespace DotNetNuke.Tests.UI.WatiN.BuildVerification
{
    [TestFixture]
    public class UpgradeTests : BVTBase
    {
        #region Private Members

        private string databasePath;
        private string siteZipFileName;
        private string upgradeZipFileName;

        #endregion

        #region SetUp and TearDown

        [SetUp]
        public void SetUp()
        {
            if (SiteType.Equals("InstallOnly"))
            {
                //Don't set up a site
                return;
            }
            //Make sure that the target folder is empty
            if (Directory.Exists(PhysicalPath))
            {
                Directory.Delete(PhysicalPath, true);
            }

            siteZipFileName = String.Format("{0}_{1}.zip", ApplicationName, SiteType);

            upgradeZipFileName = String.Format("DotNetNuke_{0}_{1}_Upgrade.zip", VersionType, TestVersion);

            //First Unzip Site Package to Website location
            ZipManager.ExtractZip(Path.Combine(TestEnvironment.PackagePath, siteZipFileName), Path.Combine(TestEnvironment.WebsitePath, "BVT"));

            //Next Unzip Upgrade Package to Website location
            ZipManager.ExtractZip(Path.Combine(TestEnvironment.PackagePath, upgradeZipFileName), PhysicalPath);

            //Copy over the log4net config file
            string sourcePath = Path.Combine(TestFilesPath, "DotNetNuke.log4net.config");
            string destPath = Path.Combine(PhysicalPath, "DotNetNuke.log4net.config");
            File.Copy(sourcePath, destPath, true);

            //Next Create Website 
            SetUpWebSite(PhysicalPath, TestUsers.DBUser.UserName, TestUsers.DBUser.Password);
            if (UpgradeVersion < new Version("4.8.0"))
            {
                //Use classic pool
                IISManager.SetApplicationPool(ApplicationName, "Classic .NET AppPool");
            }
                

            //Attach Database
            databasePath = DatabaseManager.GetDataBaseFileName(TestContext, DatabaseName, ".mdf");
            File.Copy(Path.Combine(PhysicalPath, "App_Data\\Database.mdf"), databasePath, true);
            DatabaseManager.AttachDatabase(DatabaseName, databasePath);

            //Add User
            DatabaseManager.AddUser(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password, new[] { "db_owner" });
        }


        [TearDown]
        public void TearDown()
        {
            if (SiteType.Equals("InstallOnly"))
            {
                //No site was set up, so no tear down needs to be run
                return;
            }
            //Make sure user is logged out
            ieInstance.GoTo(SiteURL + "/LogOff.aspx");
            ieInstance.ClearCache();

            //Shut down Ie
            WatiNUtil.CloseIEInstance(ieInstance);

            //Run some database updates
            string sqlAdminEmailUpdateString = @"UPDATE Users SET Email='" + TestUsers.Admin.Email + "' WHERE Username = 'admin'";
            try
            {
                //Change the Admins EmailAddress to the EmailAddress listed for the admin in TestUsers
                DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
                                                            sqlAdminEmailUpdateString);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            //Recycle IIS App Pool
            IISManager.RecycleApplicationPool(ApplicationName);
           
            //Detach and copy database to holding location
            DatabaseManager.DetachAndCopyDatabase(DatabaseName, DatabasePath, DatabaseName);

            //Remove Database Folder
            string testDatabaseDirectory = Path.GetFullPath(String.Format(@"{0}\{1}",
                                                        TestEnvironment.DatabasePath,
                                                        TestContext.Test.FullName));
            if (Directory.Exists(testDatabaseDirectory))
            {
                Directory.Delete(testDatabaseDirectory, true);
            }
        }

        #endregion

        [Test]
        [CsvData(ResourcePath = "TestData.UpgradeList.csv", HasHeader = true)]
        public void Upgrade_Should_Succeed(string version, string type)
        {
            Assert.IsFalse(type.Equals("InstallOnly"), "InstallOnly cannot be used for running an upgrade test. It is only used to indicate that the BVTs should not be run against upgraded sites.");
            
            //Open a new Internet Explorer window and navigate to the website
            ieInstance = WatiNUtil.OpenIEInstance(SiteURL, SilentMode, IETimeOut, AutoCloseIE, AutoMovePointer);
            WatiNBase homePage = new WatiNBase(ieInstance, SiteURL, DatabaseName);
            if (!Directory.Exists(CapturePath))
            {
                Directory.CreateDirectory(CapturePath);
            }

            //Wait until install completes
            if (!ieInstance.Text.Contains("Upgrading DotNetNuke"))
            {
                if (File.Exists(CapturePath + @"\UpgradeNotStarted.jpg"))
                {
                    File.Delete(CapturePath + @"\UpgradeNotStarted.jpg");
                }
                ieInstance.CaptureWebPageToFile(CapturePath + @"\UpgradeNotStarted.jpg");
               
            }
            Assert.IsTrue(ieInstance.Text.Contains("Upgrading DotNetNuke"), @"The upgade was not started. For more information on the error view the screenshot for this test under Tests\Screen Shots.");
            ieInstance.WaitUntilContainsText("Click Here To Access Your Portal", IETimeOut);
            if (File.Exists(CapturePath + @"\Upgrade.jpg"))
            {
                File.Delete(CapturePath + @"\Upgrade.jpg");
            }
            ieInstance.CaptureWebPageToFile(CapturePath + @"\Upgrade.jpg");
            if (ieInstance.Text.Contains("Error") || ieInstance.Text.Contains("Failure"))
            {
                Gallio.Framework.TestLog.WriteHighlighted("WARNING:");
                Gallio.Framework.TestLog.WriteLine(@" An Error has occurred during the upgrade however the tests may continue. For more information on the error view the screenshot for this test under Tests\Screen Captures.");
            }

            // TEMPORARY:
            //Execute a SQL Query that will disable pop ups
            //string disablePopUps = "INSERT INTO PortalSettings(PortalID, SettingName, SettingValue, CultureCode) VALUES (0, 'EnablePopups', 'false', 'en-us')";
            //try
            //{
            //    //Set the admin and host users update password value to false
            //    DatabaseManager.ExecuteSQLUpdateStringOnDatabase(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password,
            //                                                disablePopUps);
            //}
            //catch (Exception e)
            //{
            //    Gallio.Framework.TestLog.WriteLine(e);
            //}
            //END TEMP DB UPDATE

            //Click on link to go to Home Page
            ieInstance.Link(Find.ByText("Click Here To Access Your Portal")).Click();

            //Assert
            Assert.IsTrue(homePage.LogoLink.Exists);
            Assert.IsTrue(homePage.LoginLink.Exists);
            Assert.IsTrue(homePage.RegisterLink.Exists);

            LoginPage loginPage = new LoginPage(homePage);
            loginPage.LoginUser(TestUsers.Host.UserName, TestUsers.Host.Password);
            System.Threading.Thread.Sleep(1500);
            ieInstance.GoTo(SiteURL + "/Host/SQL.aspx");
            HostSQLPage SQLPage = new HostSQLPage(homePage);
            DateTime currentDate = DateTime.Now;
            int year = currentDate.Year;
            int month = currentDate.Month;
            int day = currentDate.Day;
            if (day < 2)
            {
                month = month - 1;
                if (month == 01 || month == 03 || month == 05 || month == 07 || month == 08 || month == 10 || month == 12)
                {
                    day = 31;
                }
                else if (month == 04 || month == 06 || month == 09 || month == 11)
                {
                    day = 30;
                }
                else
                {
                    if (DateTime.IsLeapYear(currentDate.Year))
                    {
                        day = 29;
                    }
                    else
                    {
                        day = 28;
                    }

                }
            }
            else
            {
                day = day - 1;
            }
            SQLPage.SQLQueryTextField.Value = "SELECT LogTypeKey, LogCreateDate, LogProperties FROM EventLog WHERE LogTypeKey LIKE '%EXCEPTION' AND LogCreateDate>'" + year + "-" + month + "-" + day + " 23:59:59.996'";
            SQLPage.ExecuteSQLLink.Click();
            System.Threading.Thread.Sleep(2000);
            if (!SQLPage.QueryResults.InnerHtml.Contains("The query did not return any data"))
            {
                TableRowCollection resultsRows = SQLPage.QueryResults.TableRows.Filter(Find.ByClass("Normal"));
                Gallio.Framework.TestLog.WriteHighlighted("WARNING: ");
                Gallio.Framework.TestLog.WriteLine("One or more exceptions occured during the upgrade however the tests may continue. For more information view the test information from this test in the Screen Captures folder. \n");
                if (File.Exists(CapturePath + @"\UpgradeException.txt"))
                {
                    File.Delete(CapturePath + @"\UpgradeException.txt");
                }
                StreamWriter sWriter = File.CreateText(CapturePath + @"\UpgradeException.txt");
                foreach (TableRow row in resultsRows)
                {
                    sWriter.WriteLine(row.OwnTableCells[0].Text + " on " + row.OwnTableCells[1] + ":");
                    sWriter.WriteLine(row.OwnTableCells[2].Text);
                }
                sWriter.Close();
            }
        }

    }
}
